<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\DbConnection\Db;

/**
 * 用户社交资料
 */
class UserSocialProfile extends Model
{
    protected $table = 'user_social_profile';

    protected $fillable = [
        'user_id', 'height', 'weight', 'marriage', 'job', 'want', 'income'
    ];

    const PROFILE_TYPE = [
        'height' => '身高',
        'weight' => '体重',
        'marriage' => '婚姻状况',
        'job' => '职业',
        'want' => '诉求',
        'income' => '年收入'
    ];

    static function getProfile($userId = 0, $dataType = 'list')
    {
        $profile = self::where('user_id', $userId)->first();
        if (!$profile) return [];
        $data = [];
        foreach (self::PROFILE_TYPE as $key => $type) {
            if ($key == 'height') $subfix = 'cm';
            elseif ($key == 'weight') $subfix = 'kg';
            else $subfix = '';
            if ($dataType == 'list') {
                $profile->{$key} && array_push($data, ['type' => $type, 'value' => $profile->{$key} . $subfix]);
            } elseif ($dataType == 'tag') {
                $profile->{$key} && array_push($data, $profile->{$key} . $subfix);
            } else {
                $data[$key] = $profile->{$key} ?: '';
            }
        }
        return $data;
    }

    /**
     * 批量获取社交资料
     */
    static function getBatchProfile($userIds = 0, $dataType = 'tag')
    {
        if (empty($userIds)) return [];
        $profiles = self::whereIn('user_id', $userIds)->get()->toArray();
        $data = [];
        $validKeys = ['height', 'weight', 'job', 'want'];
        foreach ($profiles as $profile) {
            foreach (self::PROFILE_TYPE as $key => $type) {
                if (!in_array($key, $validKeys)) continue;
                if (!isset($data[$profile['user_id']])) $data[$profile['user_id']] = [];
                if ($dataType == 'tag') {
                    if ($key == 'height') $subfix = 'cm';
                    elseif ($key == 'weight') $subfix = 'kg';
                    else $subfix = '';
                    $profile[$key] && array_push($data[$profile['user_id']], $profile[$key] . $subfix);
                }
            }
        }
        return $data;
    }

    /**
     * 更新资料
     */
    static function updateProfile($userId = 0, $info = [])
    {
        return self::updateOrCreate(['user_id' => $userId], $info);
    }
}
